package org.aileen.springbook.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.aileen.springbook.Constant.Constant;
import org.aileen.springbook.model.Result;
import org.aileen.springbook.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //注入JSON对象
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * true : 放行,继续执行目标方法
     * false : 拦截,不执行目标方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request , HttpServletResponse response , Object handler) throws Exception {
        log.info("效验用户是否登录");
        HttpSession session = request.getSession();//从请求中获取session对象
        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.USER_SESSION_KEY);
        //从session中获取值,获取到说明用户已经登录,如果没有获取到则说明用户没有登录
        if (userInfo == null){
            log.warn("用户未登录,拦截请求");
            //用户未登录
            response.setStatus(401);//设置状态码为401
            //对响应状态码进行设定->将后端返回的内容以JSON形式传输给HTTP请求
            response.setContentType("application/json;charset=UTF-8");
            Result result = Result.fail("用户未登录");
            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
            return false; //拦截,不执行目标方法
        }
        log.info("用户登录效验通过");
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("目标方法后执行的代码");
//    }
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("视图渲染完成后执行的代码");
//    }
}
